﻿#include "VideoDecoder.h"
#include <QImage>
#include <QDebug>
#include <opencv2/opencv.hpp>

VideoDecoder::VideoDecoder(QObject *parent) : QObject(parent) {
    m_currentPosition = 0;
}

void VideoDecoder::open(const QString &filePath) {
    stop();

    m_cap.open(filePath.toStdString(), cv::CAP_FFMPEG);
    if(!m_cap.isOpened()) {
        qWarning() << "Failed to open video:" << filePath;
        return;
    }

    m_running = true;
    m_decodeThread = std::thread(&VideoDecoder::decodeLoop, this);

    // 通知视频总时长
    double fps = m_cap.get(cv::CAP_PROP_FPS);
    int frameCount = m_cap.get(cv::CAP_PROP_FRAME_COUNT);
    emit durationChanged(static_cast<int>(frameCount * 1000 / fps));
}

void VideoDecoder::decodeLoop() {
    cv::Mat frame;
    auto lastTime = std::chrono::high_resolution_clock::now();

    while(m_running) {
        {
            QMutexLocker lock(&m_mutex);
            if(!m_cap.read(frame) || frame.empty()) break;
        }

        // 转换颜色空间并深拷贝
        cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
        QImage qimg(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);

        // 计算并发送时间戳
        auto now = std::chrono::high_resolution_clock::now();
        int elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
                          now - lastTime).count();
        lastTime = now;

        m_currentPosition = elapsed;
        emit positionChanged(elapsed);
        emit frameReceived(qimg.copy());

        // 动态帧率控制
        double fps = m_cap.get(cv::CAP_PROP_FPS);
        if(fps > 0) {
            int delay = static_cast<int>(1000 / fps);
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        }
    }
    m_running = false;
}

void VideoDecoder::stop() {
    m_running = false;
    if(m_decodeThread.joinable()) m_decodeThread.join();
    if(m_cap.isOpened()) m_cap.release();
}

void VideoDecoder::setPosition(int ms){
    m_currentPosition = ms;
}

VideoDecoder::~VideoDecoder() {
    stop();
}
